'''
Author: WuFeng <763467339@qq.com>
Date: 2024-11-20 10:25:34
LastEditTime: 2024-11-20 13:12:24
LastEditors: WuFeng <763467339@qq.com>
Description: pdf加水印
FilePath: \markdown-magic\python\service\pdfWatermark.py
Copyright 版权声明

字体下载网站： https://www.aigei.com/s?type=font

'''
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

import PyPDF2

# 使用 reportlab 创建一个包含水印的 PDF 页
def create_watermark(watermark_text, output_path, font):

    # 注册中文字体
    font_path = f'./assets/font/{font}.ttf'  # 请替换为你的中文字体文件路径
    pdfmetrics.registerFont(TTFont('CustomFont', font_path))

    c = canvas.Canvas(output_path, pagesize=letter)
    width, height = letter
    
    # 设置水印字体和颜色
    # c.setFont("Helvetica", 60)
    c.setFont("CustomFont", 60)
    c.setFillColorRGB(0.5, 0.5, 0.5, alpha=0.8)  # 半透明灰色
    
    # 计算水印位置
    # text_width = c.stringWidth(watermark_text, "Helvetica", 60)
    text_width = c.stringWidth(watermark_text, "CustomFont", 60)
    x = (width - text_width) / 2
    y = height / 2
    
    # 添加水印
    c.saveState()
    c.translate(x, y)
    c.rotate(45)
    c.drawString(0, 0, watermark_text)
    c.restoreState()
    
    c.showPage()
    c.save()

# 将水印添加到 PDF 文件的每一页
def add_watermark(input_pdf, output_pdf, watermark_pdf):
    # 打开输入 PDF 文件
    input_pdf_reader = PyPDF2.PdfReader(input_pdf)
    
    # 打开水印 PDF 文件
    watermark_pdf_reader = PyPDF2.PdfReader(watermark_pdf)
    watermark_page = watermark_pdf_reader.pages[0]
    
    # 创建输出 PDF 文件
    output_pdf_writer = PyPDF2.PdfWriter()
    
    # 遍历输入 PDF 文件的每一页
    for page_num in range(len(input_pdf_reader.pages)):
        page = input_pdf_reader.pages[page_num]
        
        # 将水印页合并到当前页
        page.merge_page(watermark_page)
        
        # 将合并后的页添加到输出 PDF 文件
        output_pdf_writer.add_page(page)
    
    # 写入输出 PDF 文件
    with open(output_pdf, 'wb') as output_file:
        output_pdf_writer.write(output_file)

# # 使用示例
# input_pdf = 'path/to/your/input.pdf'
# output_pdf = 'path/to/your/output_with_watermark.pdf'
# watermark_pdf = 'path/to/your/watermark.pdf'

# # 创建水印 PDF 文件
# create_watermark("Sample Watermark", watermark_pdf)

# # 将水印添加到 PDF 文件
# add_watermark(input_pdf, output_pdf, watermark_pdf)